package org.csu.mybigpro.service;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;

import java.net.InetSocketAddress;
import java.net.Proxy;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class LiveRecordingApiService {

    @Value("${livekit.url}")
    private String livekitUrl;

    @Value("${livekit.api.key}")
    private String livekitApiKey;

    @Value("${livekit.api.secret}")
    private String livekitApiSecret;

    private final ObjectMapper objectMapper = new ObjectMapper();

    public String startRecording(String roomName) throws Exception {
        // 1. 生成包含正确权限的Token
        String token = createApiToken();

        // 2. 使用ObjectMapper安全地构建JSON
        Map<String, Object> fileDetails = new HashMap<>();
        fileDetails.put("filepath", String.format("livekit-recordings/%s-%d.mp4", roomName, System.currentTimeMillis()));
        Map<String, Object> outputPayload = new HashMap<>();
        outputPayload.put("file", fileDetails);
        Map<String, Object> requestBodyMap = new HashMap<>();
        requestBodyMap.put("room_name", roomName);
        requestBodyMap.put("output", outputPayload);
        String jsonBody = objectMapper.writeValueAsString(requestBodyMap);

        // 3. 使用带代理的RestTemplate发送请求
        Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("127.0.0.1", 7890));
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        requestFactory.setProxy(proxy);
        RestTemplate restTemplate = new RestTemplate(requestFactory);
        String apiUrl = livekitUrl + "/twirp/livekit.Egress/StartRoomCompositeEgress";
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.setBearerAuth(token);
        HttpEntity<String> entity = new HttpEntity<>(jsonBody, headers);

        try {
            ResponseEntity<String> response = restTemplate.postForEntity(apiUrl, entity, String.class);
            if (response.getStatusCode().is2xxSuccessful() && response.getBody() != null) {
                Map<String, String> responseMap = objectMapper.readValue(response.getBody(), new TypeReference<>() {});
                return responseMap.get("egress_id");
            } else {
                throw new RuntimeException("API 请求成功但响应无效, 状态码: " + response.getStatusCode());
            }
        } catch (HttpClientErrorException e) {
            throw new RuntimeException("API 请求失败，状态码: " + e.getStatusCode() + ", 响应体: " + e.getResponseBodyAsString());
        }
    }

    public void stopRecording(String egressId) throws Exception {
        String token = createApiToken();
        String jsonBody = String.format("{\"egress_id\":\"%s\"}", egressId);
        Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("127.0.0.1", 7890));
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        requestFactory.setProxy(proxy);
        RestTemplate restTemplate = new RestTemplate(requestFactory);
        String apiUrl = livekitUrl + "/twirp/livekit.Egress/StopEgress";
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.setBearerAuth(token);
        HttpEntity<String> entity = new HttpEntity<>(jsonBody, headers);
        restTemplate.postForEntity(apiUrl, entity, String.class);
    }

    // 【最终修正】恢复为您原始的、正确的Token权限设置
    private String createApiToken() {
        Map<String, Object> videoGrant = new HashMap<>();
        videoGrant.put("roomRecord", true); // 使用您最初的、正确的权限

        return Jwts.builder()
                .setIssuer(livekitApiKey)
                .setSubject(livekitApiKey)
                .setIssuedAt(Date.from(Instant.now()))
                .setExpiration(Date.from(Instant.now().plusSeconds(300)))
                .claim("video", videoGrant)
                .signWith(Keys.hmacShaKeyFor(livekitApiSecret.getBytes(StandardCharsets.UTF_8)), SignatureAlgorithm.HS256)
                .compact();
    }
}